package cn.tworice.client.web;

import cn.tworice.client.service.NetworkService;
import cn.tworice.common.vo.RequestResult;
import cn.tworice.vo.Entity;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.maxmind.geoip2.exception.AddressNotFoundException;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.List;

@RequestMapping("/client/network")
@RestController
@CrossOrigin
public class NetworkClient {

    @Resource
    private NetworkService service;

    /**
     * 测速接口
     * @return cn.tworice.common.vo.RequestResult
     * @author 二饭 [2023/4/1]
     **/
    @GetMapping("speed")
    public RequestResult speed() {
        String url = "https://www.baidu.com";
        try {
            return RequestResult.success(201)
                    .appendData("speed",service.getSpeed(url))
                    .appendData("delay",service.getDelay());
        } catch (Exception e) {
            return RequestResult.error("无法访问主机");
        }
    }

    @PostMapping("inducts")
    public void inducts(String arr, HttpServletResponse response) throws IOException{
        List<Entity> entities = JSON.parseArray(arr, Entity.class);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("数据表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Entity.class).sheet("模板").doWrite(entities);
    }

    /**
     * 网络连接安全检测
     * @param url
     * @return cn.tworice.common.vo.RequestResult
     * @author 二饭 [2023/4/1]
     **/
    @GetMapping("connect")
    public RequestResult connect(String url) {
        try {
            String connectionSecure = service.isConnectionSecure(url);
            return RequestResult.success(201).appendData("result",connectionSecure);
        } catch (Exception e) {
            return RequestResult.success(201).appendData("result",e.getMessage());
        }
    }

    /**
     * 当前网络环境是否安全
     * @return cn.tworice.common.vo.RequestResult
     * @author 二饭 [2023/4/1]
     **/
    @GetMapping("env")
    public RequestResult connect() {
        try {
            String wifiSSID = service.getCurrentWiFiSSID();
            if (wifiSSID != null) {
                String state = "网络不安全，存在劫持可能";
                if (service.isWiFiSecure(wifiSSID)) {
                    state = "网络安全";
                }
                return RequestResult.success(201).appendData("name", wifiSSID).appendData("state",state);
            } else {
                return RequestResult.success(201).appendData("name", "未连接到网络");
            }
        } catch (IOException e) {
            return RequestResult.error(e.getMessage());
        }
    }

    /**
     * DNS劫持检测
     * @param domain 域名
     * @return cn.tworice.common.vo.RequestResult
     * @author 二饭 [2023/4/13]
     **/
    @GetMapping("dns")
    public RequestResult dns(String domain) throws UnknownHostException, MalformedURLException {
        domain = service.parseDomain(domain);
        return RequestResult.success()
                .appendData("dns", service.dns(domain))
                .appendData("ipAddr", service.getIPAddrByName(domain))
                .appendData("host",domain);
    }

    @GetMapping("belonging")
    public RequestResult belonging(String domain) throws IOException, GeoIp2Exception {
        domain = service.parseDomain(domain);
        List<String> ipAddrByName = service.getIPAddrByName(domain);
        for (String ip : ipAddrByName) {
            String countryName = "";
            try {
                countryName = service.getCountryName(ip);
            }catch (AddressNotFoundException exception){
                return RequestResult.error("归属地异常").appendData("result", "域名【"+domain+"】所属IP【"+ip+"】归属地未知。");
            }
            if (!countryName.equals("中国")) {
                return RequestResult.error("归属地异常").appendData("result", "域名【"+domain+"】所属IP【"+ip+"】归属地为【"+countryName+"】。");
            }
        }
        return RequestResult.success().appendData("result", "所属IP归属地为中国，无异常。");
    }

}
